from django.template.loader import render_to_string
from django.conf import settings
from datetime import datetime, timedelta
import base64, hmac, hashlib, re

def ipn_decode(data):
    encoded = data.get('encoded', '')
    decoded = base64.b64decode(encoded)
    lines = decoded.split("\n")
    rc = re.compile("^INVOICE=(\d+):STATUS=(PAID|DENIED|EXPIRED)")
    results = {}
    for line in lines:
        m = rc.search(line)
        if m:
            invoice_id = int(m.group(1))
            status = str(m.group(2))
            results[invoice_id]=status
    return results

def quickEPay(**kwargs):
    return makeEPayRequest(email=settings.EPAY_EMAIL, passkey=settings.EPAY_PASSKEY, demo=False, **kwargs)

def makeEPayRequest(MIN='', email='email@example.com', invoice=0, amount=0, currency='BGN', descr='payment', encoding='utf-8', passkey='', url_ok='', url_cancel='', pay_button_class='', pay_button_text='', demo=False):
    result = ''
    if MIN:
        rawdata = u"MIN=%s\n" % MIN
    else:
        rawdata = u"EMAIL=%s\n" % email
    rawdata += u"INVOICE=%d\n" % invoice
    rawdata += u"AMOUNT=%.2f\n" % amount
    rawdata += u"CURRENCY=%s\n" % currency
    dtn = datetime.now() + timedelta(hours=24)
    rawdata += u"EXP_TIME=%02d.%02d.%d %02d:%02d\n" % (dtn.day, dtn.month, dtn.year, dtn.hour, dtn.minute)
    rawdata += u"DESCR=%s" % descr
    encoded = base64.b64encode(rawdata)
    h = hmac.new(passkey, encoded, hashlib.sha1)
    checksum = h.hexdigest()
    EPAY_URL = "https://devep2.datamax.bg/ep2/epay2_demo/" if demo else "https://www.epay.bg/"
    PAY_BUTTON_CLASS = pay_button_class
    PAY_BUTTON_TEXT = pay_button_text
    return render_to_string('payments/epay_form.html', locals())
